package com.dunjx.user.service.impl;

import com.dunjx.fast.feign.FastFeign;
import com.dunjx.user.pojo.*;
import com.dunjx.user.dao.*;
import com.dunjx.user.service.UserService;
import com.github.pagehelper.*;
import entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/****
 * @Author:admin
 * @Description:User业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private FastFeign fastFeign;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private RegionCityMapper regionCityMapper;


    /**
     * User条件+分页查询
     *
     * @param user 查询条件
     * @return 分页结果
     */
    @Override
    public PageInfo<User> findPage(User user) {
        //分页
        PageHelper.startPage(user.getPageNo(), user.getPageSize());
        //搜索条件构建
        Example example = createExample(user);
        List<User> users = userMapper.selectByExample(example);
        for (User userInfo : users) {
            String address = userInfo.getAddress();
            String[] split = address.split(",");

            String isMobileCheck = userInfo.getIsMobileCheck();
            if ("0".equals(isMobileCheck)) {
                userInfo.setIsMobileCheck("认证");
            } else if ("1".equals(isMobileCheck)) {
                userInfo.setIsMobileCheck("未认证");
            }

            String isEmailCheck = userInfo.getIsEmailCheck();
            if ("0".equals(isEmailCheck)) {
                userInfo.setIsEmailCheck("认证");
            } else if ("1".equals(isEmailCheck)) {
                userInfo.setIsEmailCheck("未认证");
            }

            String  sex= userInfo.getSex();
            if ("1".equals(sex)) {
                userInfo.setSex("男");
            } else if ("2".equals(sex)) {
                userInfo.setSex("女");
            } else if ("3".equals(sex)) {
                userInfo.setSex("保密");
            }
            List<String> cityInfos = new ArrayList();
            for (String s : split) {
                RegionCity regionCityInfo = regionCityMapper.selectByPrimaryKey(Integer.valueOf(s));
                cityInfos.add(regionCityInfo.getName());
            }
            userInfo.setAddress(org.apache.commons.lang3.StringUtils.join(cityInfos, ","));
        }
        //执行搜索
        return new PageInfo<User>(users);
    }


    /**
     * User条件查询
     *
     * @param user
     * @return
     */
    @Override
    public List<User> findList(User user) {
        //构建查询条件
        Example example = createExample(user);
        //根据构建的条件查询数据
        return userMapper.selectByExample(example);
    }


    /**
     * User构建查询对象
     *
     * @param user
     * @return
     */
    public Example createExample(User user) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (user != null) {
            // 用户表id
            if (!StringUtils.isEmpty(user.getId())) {
                criteria.andEqualTo("id", user.getId());
            }
            // 用户编号
            if (!StringUtils.isEmpty(user.getUid())) {
                criteria.andEqualTo("uid", user.getUid());
            }
            // 用户名
            if (!StringUtils.isEmpty(user.getUsername())) {
                criteria.andLike("username", "%" + user.getUsername() + "%");
            }
            // 真实姓名
            if (!StringUtils.isEmpty(user.getRealname())) {
                criteria.andLike("realname", "%" + user.getRealname() + "%");
            }
            // 性别 1 男 2 女  3 保密
            if (!StringUtils.isEmpty(user.getSex())) {
                criteria.andEqualTo("sex", user.getSex());
            }

            // 昵称
            if (!StringUtils.isEmpty(user.getNikeName())) {
                criteria.andEqualTo("nikeName", user.getNikeName());
            }
            // 邮箱
            if (!StringUtils.isEmpty(user.getEmail())) {
                criteria.andEqualTo("email", user.getEmail());
            }
            // 绑定手机号
            if (!StringUtils.isEmpty(user.getPhone())) {
                criteria.andEqualTo("phone", user.getPhone());
            }
            // 状态 1 禁用 2 注销 0正常
            if (!StringUtils.isEmpty(user.getStatus())) {
                criteria.andEqualTo("status", user.getStatus());
            }

            // QQ账号
            if (!StringUtils.isEmpty(user.getQqNumber())) {
                criteria.andEqualTo("qqNumber", user.getQqNumber());
            }
            // 电话是否认证 0 认证 1 未认证
            if (!StringUtils.isEmpty(user.getIsMobileCheck())) {
                criteria.andEqualTo("isMobileCheck", user.getIsMobileCheck());
            }
            // 邮箱是否认证 0 认证 1 未认证
            if (!StringUtils.isEmpty(user.getIsEmailCheck())) {
                criteria.andEqualTo("isEmailCheck", user.getIsEmailCheck());
            }
            // 微信账号
            if (!StringUtils.isEmpty(user.getWechatNumber())) {
                criteria.andEqualTo("wechatNumber", user.getWechatNumber());
            }
            // 备注
            if (!StringUtils.isEmpty(user.getRemark())) {
                criteria.andEqualTo("remark", user.getRemark());
            }


        }
        return example;
    }


    /**
     * 根据ID查询User
     *
     * @param id
     * @return
     */
    @Override
    public User findById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询User全部数据
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    /**
     * 根据id 添加/修改用户
     *
     * @param user
     */
    @Override
    public void save(User user, MultipartFile multipartFile){
        // 头像地址
        String urlPath = "";
        if (multipartFile != null) {
            Result upload = fastFeign.upload(multipartFile);
            urlPath = (String) upload.getData();
        }
        boolean boo = false;
        if (StringUtils.isEmpty(urlPath)) {
            boo = false;
        } else {
            boo = true;
        }


        /*地址 逗号分割  地址id  1,2,3*/
        String address = "";
        if (user.getCity() != null) {
            String str = Arrays.toString(user.getCity());
            address = str.substring(1, str.length()-1);
            address  = address.replaceAll(" ", "");
            user.setAddress(address);
        }

        if (StringUtils.isEmpty(user.getId())) {
            if (boo) {
                user.setHeadUrl(urlPath);
            }
            // 电话是否认证
            user.setIsMobileCheck("1");
            // 邮箱是否认证
            user.setIsEmailCheck("1");
            if (StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(bCryptPasswordEncoder.encode("abcdefg123."));
            }
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            // 用户id
            user.setId(idWorker.nextId() + "");
            // 注册时间
            user.setRegisterTime(new Date());
            // 状态 1 禁用 2 注销 0正常
            user.setStatus("1");
            // 用户唯一编号
            user.setUid("UID." + new NumberGenerate().getNumber());
            userMapper.insert(user);
        } else {
            if (boo) {
                User userInfo = userMapper.selectByPrimaryKey(user.getId());
                String headUrl = userInfo.getHeadUrl();
                if (!StringUtils.isEmpty(headUrl)) {
                    // 删除图片
                    int groupStart = org.apache.commons.lang3.StringUtils.ordinalIndexOf(headUrl, "/", 3);
                    int groupEnd = org.apache.commons.lang3.StringUtils.ordinalIndexOf(headUrl, "/", 4);
                    String groupName = headUrl.substring(groupStart + 1, groupEnd);
                    String fileName = headUrl.substring(groupEnd + 1);
                    fastFeign.delete(groupName, fileName);
                }
                if (boo) {
                    user.setHeadUrl(urlPath);
                }
            }
            userMapper.updateByPrimaryKeySelective(user);
        }

    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public User findOneUser(String username) {
        User user = new User();
        user.setUsername(username);
        return userMapper.selectOne(user);
    }


}
